# coding=utf-8
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many


def record_rds():
    asapi_data = request_asapi(1, "Rds", "2016-04-07-FUWU", "DescribeDBInstances")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for i in asapi_data['Items']['DBInstance']:
        tmp_tuple = (
            i['DBInstanceId'], i['Category'], i['DBInstanceType'], i['DBInstanceNetType'], i['InstanceNetworkType'],
            i['Department'], i['DepartmentName'], str(i['ReadOnlyDBInstanceIds']['ReadOnlyDBInstanceId']), i['Engine'],
            i['EngineVersion'], i['ResourceGroup'], i['ResourceGroupName'], i['DBInstanceStatus'], i['DBInstanceClass'],
            i['VpcId'], i['VSwitchId'], i['LockMode'], i['DBInstanceStorageType'], i['ConnectionMode'], i['Vip'],
            i['CreateTime'], datetime.now())
        values_list.append(tmp_tuple)
    table = 'c_rds_info'
    fields = "db_instance_id,category,db_instance_type,db_instance_net_type,instance_network_type,department,department_name,read_only_db_instance_ids,engine,engine_version,resource_group,resource_group_name,db_instance_status,db_instance_class,vpc_id,vswitch_id,lock_mode,db_instance_storage_type,connection_mode,vip,create_time,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_rds_info', methods=['POST'])
def record_rds_api():
    success = record_rds()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
